<?php
namespace app\index\controller;
use app\index\model\Company;
use think\Controller;
use think\Db;

class Chat extends Controller
{


	public function index()
	{
        $type     = input('param.type', 0);
        $userId   = input('param.user_id', 0);
        $longitude= input('param.longitude');  //经度
        $latitude = input('param.latitude');  //纬度

		if (empty($longitude) || empty($latitude)) {
            $this->ajaxReturn(null, '无经纬度', 201);
        }

        $field = '*';
        $order = 'id desc';

        ## 个人
        if($type==1){

            $userId && $where[] = ['id','<>',$userId];
            $where[] = ['nickName','<>',''];
            $where[] = ['status','in',[1,2]];


            $count = db('user')->where($where)->count();

            $Page = new \VuePage($count,10);

            $field = '';
           if($latitude && $latitude){
                         $distance = 'ROUND(
                    6378.138 * 2 * ASIN(SQRT(POW(SIN(('
                             .$latitude.' * PI() / 180 - latitude * PI() / 180) / 2),2) + COS('
                             .$latitude.' * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN(('
                             .$longitude.' * PI() / 180 - longitude * PI() / 180) / 2),2))) * 1000)';

                         $field = '*,'.$distance.' AS distance';
                         $order = 'distance asc';
           }
            $whereStr = "where nickName<>'' and status in (1,2)";
            if ($userId) {
                $whereStr.= ' and id <> '.$userId;
            }
//            $limitStr = '';
            $limitStr = " limit {$Page->getStart()}, {$Page->getEnd()}";
            # 运行 运行 groupby
            Db::query("set @@global.sql_mode=(select replace(@@global.sql_mode,'ONLY_FULL_GROUP_BY',''))");
            $sql = "
                    SELECT {$field} from tp_user as U LEFT JOIN 
                    (
                    SELECT * from (SELECT from_client_id,`status` as ccStatus,ctime as cctime from tp_chat 
                    where to_client_id= {$userId} and `status` =0 ORDER BY ctime desc ) as L 
                    GROUP BY L.from_client_id 
                    ) as C on (U.id  =  C.from_client_id) {$whereStr} 
                    ORDER BY ccstatus DESC,cctime DESC, distance ASC  {$limitStr}";

            $list = Db::query($sql);
            if($list){
                foreach($list as $k=>$v){
                    $w = '(from_client_id='.$userId.' and to_client_id='.$v['id']. ') or (from_client_id='.$v['id'].' and to_client_id='.$userId.' )';
                    $content = db('chat')->where($w)->order('ctime desc')->value('content');

                    $list[$k]['content'] = !empty($content)?$content:'';
                    // 未读消息；
                    $whereNoRead = '(from_client_id='.$v['id'].' and to_client_id='.$userId.' )';
                    $chatNoReadCount = db('chat')->where($whereNoRead)->where('status',0)->count();
                    if ($chatNoReadCount>0) {
                        $list[$k]['chat_status'] = 0; // 未读
                    } else {
                        $list[$k]['chat_status'] = 1; // 已读
                    }
                    # 添加user_id:
                    $list[$k]['user_id'] =   $list[$k]['id'];
//                    $v->status = 1; //表示已读
//                    $v->save();
                }
            }
            $Page->setData($list);
            $return = $Page->indexjson();

        }else if($type==2){ #企业

            if($latitude && $latitude){
                $distance = 'ROUND(
                    6378.138 * 2 * ASIN(SQRT(POW(SIN(('
                    .$latitude.' * PI() / 180 - latitude * PI() / 180) / 2),2) + COS('
                    .$latitude.' * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN(('
                    .$longitude.' * PI() / 180 - longitude * PI() / 180) / 2),2))) * 1000)';

                $field = 'id,latitude,longitude,user_id,company_name nickName,logo avatarUrl,'.$distance.' AS distance';
                $order = 'distance asc';
            }

            $userId && $where[] = ['user_id','<>',$userId];
            $where[] = ['status','=',2];
            $count = db('company')->where($where)->count();
            $Page = new \VuePage($count,10);
            $list = db('company')->where($where)->order($order)->limit($Page->getStart(),$Page->getEnd())->field($field)->select();
            if($list){
                foreach($list as $k=>$v){
                    $w = '(from_client_id='.$userId.' and to_client_id='.$v['user_id']. ') or (from_client_id='.$v['user_id'].' and to_client_id='.$userId.' )';
                    $content = db('chat')->where($w)->order('ctime desc')->value('content');
                    $list[$k]['content'] = !empty($content)?$content:'';
                    // 未读消息；
                    $whereNoRead = '(from_client_id='.$v['user_id'].' and to_client_id='.$userId.' )';
                    $chatNoReadCount = db('chat')->where($whereNoRead)->where('status',0)->count();
//                    var_dump($chatNoReadCount);die;
                    if ($chatNoReadCount>0) {
                        $list[$k]['chat_status'] = 0; // 未读
                    } else {
                        $list[$k]['chat_status'] = 1; // 已读
                    }
                }
            }
            $Page->setData($list);
            $return = $Page->indexjson();
        }



        $return['info'] = 'ok';
        $return['status'] = 200;
        $return['statistics'] = $this->getCountNoReadCount($userId);
        $this->_ajaxReturn($return);
	}


    /**
     * 重新排序
     *
     * @param [type] $array
     * @param [type] $field
     * @param string $sort
     * @return void
     */
    function arraySequence($array, $field, $sort = 'SORT_ASC') {
        $arrSort=array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }


    /**
     * 历史数据 聊天记录
     *
     * @return void
     */
    public function history()
    {
        $from_client_id = input('get.from_client_id');
        $to_client_id = input('get.to_client_id');
        if (empty($from_client_id) || empty($to_client_id)) {
            $this->ajaxReturn(null, '参数错误', 201);
        }

        $where = '(from_client_id='.$from_client_id.' and to_client_id='.$to_client_id. ') or (from_client_id='.$to_client_id.' and to_client_id='.$from_client_id.' )';
        $order = 'ctime desc';
        $count = db('chat')->where($where)->count();
        $Page = new \VuePage($count,10);
        $list = db('chat')->where($where)->order($order)->limit($Page->getStart(),$Page->getEnd())->select();
        // 修改消息为已读；
        db('chat')->where($where)->update([
            'status' => 1,
        ]);

        if(!empty($list)) $list = $this->arraySequence($list,'id');
        $Page->setData($list);
        $return = $Page->indexjson();

        $return['info'] = 'ok';
        $return['status'] = 200;
        $this->_ajaxReturn($return);
    }

    # 获取 未读消息；
    public function getCountNoReadCount($user_id)
    {
        # 个人未读消息--排除公司用户
        # 企业未读消息
        // 查询公司用户--- 用于排除公司用户--查询个人
        $companyUser = Company::getSuccessAll()->toArray();
        $companyUserIds =  array_map(function($item){
            return $item['user_id'];
        }, $companyUser);

        $whereNoRead = 'to_client_id='.$user_id;
        $UserNoReadCountAll = db('chat')
            ->whereNotIn('from_client_id',$companyUserIds)
            ->where($whereNoRead)
            ->where('status',0)
            ->count();

        $CompanyNoReadCount = db('chat')
            ->whereIn('from_client_id',$companyUserIds)
            ->where($whereNoRead)
            ->where('status',0)
            ->count();
        return [
            'user_no_readcount' => $UserNoReadCountAll,
            'company_no_readcount' => $CompanyNoReadCount,
        ];

    }
}
